<template>
  <div class="login">
    <div class="form-box">
      <p class="title">航动智慧工牌</p>
      <a-form
        ref="loginBox"
        :model="formState"
        name="basic"
        :label-col="{span:0}"
        :wrapper-col="{ span: 24 }"
        autocomplete="off"
        :rules="rules"
        size="large"
        @validate="checkForm"
        @finish="onFinish"
        @finishFailed="onFinishFailed" >
        <a-form-item
          name="uname">
          <a-input  v-model:value="formState.uname" placeholder="请输入用户名" allow-clear>
            <template #prefix>
              <UserOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input> 
        </a-form-item>

        <a-form-item
          name="psd">
          <a-input-password  v-model:value="formState.psd" placeholder="请输入密码" type="password" allow-clear>
            <template #prefix>
              <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item name="code" class="input-wrap">
          <a-input class="code-input"  v-model:value="formState.code" placeholder="请输入验证码" type="code" allow-clear>
          </a-input>
          <div class="img-box pointer" @click="updateCode">
            <img :src="codeUrl" alt="">
          </div>
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 0, span: 24 }">
          <a-button class="login-btn"  type="primary" html-type="submit">登录</a-button>
        </a-form-item>
      </a-form>


    </div>
  </div>
</template>

<script setup>
  import { reactive,ref,onMounted } from 'vue';
  import { useRouter } from "vue-router";
  import { message } from 'ant-design-vue';
  import axios from 'axios';
  import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
  import apiBox from '@/request/api.js';
  import {useStore} from '../stores/index.js'




  // 定义路由
  const router = useRouter();
  const store = useStore();
  
  // 用户名+密码
  // "password": "123456",
  // "username": "13691716642"
  const formState = reactive({
    uname: '',
    psd: '',
    code:''
  });

  let validCheck = ref('');
  let codeUrl = ref('');
  let getCode = ()=>{
    axios.get('http://43.139.30.253:38005/v1/user/captcha').then(res => {

      console.log('验证码信息',res.data);
      codeUrl.value=res.data.imgBase64String;
      validCheck.value=res.data.validCheck;
    })

  }
  let updateCode = ()=>{
    getCode();
  }
  getCode();


  // 表单验证规则
  let loginBox = ref();
  let usernameCheck = async (_rule, value) => {
    if (value === '') {
      return Promise.reject('请输入用户名');
    } else {
      if (formState.username !== '') {
        loginBox.value.validateFields('验证通过');
      }
      return Promise.resolve();
    }
  };
  let passwordCheck = async (_rule, value) => {
    if (value === '') {
      return Promise.reject('请输入密码');
    } else {
      if (formState.password !== '') {
        loginBox.value.validateFields('验证通过');
      }
      return Promise.resolve();
    }
  };
  let codeCheck = async (_rule, value) => {
    if (value === '') {
      return Promise.reject('请输入验证码');
    } else {
      if (formState.code !== '') {
        loginBox.value.validateFields('验证通过');
      }
      return Promise.resolve();
    }
  };

  const rules = {
    uname: [{
      required: true,
      validator: usernameCheck,
      trigger: 'change',
    }],
    psd: [{
      required: true,
      validator: passwordCheck,
      trigger: 'change',
    }],
    code: [{
      required: true,
      validator: codeCheck,
      trigger: 'change',
    }],
  };

  // 验证成功
  const onFinish = async(values) => {
    if(values.uname&&values.psd&&values.code){

      axios.post('http://43.139.30.253:38005/v1/user/login', {
        password: formState.psd,
        username:formState.uname,
        validCheck: validCheck.value,
        validCode: formState.code
      }, {

      }).then(res=>{
        console.log('登录',res)
        if(res.data.token){
          store.$patch({
            username:'admin',
            id:'1',
            authBox:['home'],
            token:res.data.token
          })

          message.success('登录成功');
          router.push('/');
        }else{
          message.info('用户名或密码错误');
        }
        getCode();

      })

      
    }else{
      message.info('请输入登录信息');
    }

  };

  // 验证失败
  const onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo);
  };

  // 表单重置
  const resetForm = () => {
    loginBox.value.resetFields();
  };

  // 表单验证时触发
  const checkForm = (...args) => {

  };


</script>

<style lang="scss" scoped>
  .pointer {cursor: pointer;}
  .title {
    font-size: 44px;
    margin-bottom: 30px;
    color: rgba(0,0,0,.85);
    font-weight: 600;
    text-align: center;
    background: linear-gradient(120deg, #4abf8a,#3eaf7c 30%, #3e71af 100%);
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
  }
  .login {
    height: 100vh;
    width: 100%;
    min-height: 100%;
    background: #f0f2f5 url(../../public/images/bj.svg) no-repeat 50%;
    background-size: cover;

    .form-box {
      width: 400px;
      margin:0 auto;
      padding-top: 15%;
      .login-btn {
        width: 100%;
      }
      
    }
  }

  .code-input {width: 272px;}
  .img-box {
    width: 115px;
    border-radius:8px;
    overflow: hidden;
    img {width: 100%;}
  }
</style>